package com.idrem.db.operation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.idrem.data.model.Product;
import com.idrem.data.model.ProductRS;
import com.idrem.db.DBManager;
import com.idrem.db.model.ProductModel;

public class ProductDBOperation {

	private String TAG = "PRODUCT DB Operation: ";
	
	private SQLiteDatabase mSQLiteDatabase;
	private DBManager dbManager;

	public ProductDBOperation(Context context) {
		dbManager = new DBManager(context);
	}

	public ProductDBOperation open() {
		mSQLiteDatabase = dbManager.getWritableDatabase();
		return this;
	}

	public void close() {
		dbManager.close();
	}

	/**
	 * Insert an article model into table.
	 * @param dbArticleModel
	 * @return
	 */
	public void insertProducts(ProductRS prors) {
		if (prors != null && prors.getProducts() != null) {
			for (Product pro:prors.getProducts()) {
				
				if (isExistsInProductTable(pro.getPno())) {
					updateProduct(pro);
				} else {
					insertProduct(pro);
				}
				
			}
		}

		
	}
	
	private long insertProduct(Product pro) {

		ContentValues initialValues = createProductValues(pro);

		return mSQLiteDatabase.insert(DBManager.DB_PRODUCT_TABLE, null,
				initialValues);
	}
	
	/**
	 * Check the article exist or not.
	 * @param articleId
	 * @return
	 */
	public boolean isExistsInProductTable(String pno) {
		
		String countSql = "SELECT * FROM " + DBManager.DB_PRODUCT_TABLE
		+ " WHERE " + DBManager.PRODUCT_PNO + "= '" + pno + "'";
		
		Cursor cursor = mSQLiteDatabase.rawQuery(countSql, null);
		
		if(cursor.getCount() == 0) {
			cursor.close();
			return false;
		}else {
			cursor.close();
			return true;
		}
	}
	
	public boolean updateProduct(Product pro) {
		
		ContentValues updateValues = createProductValues(pro);
		
		return mSQLiteDatabase.update(DBManager.DB_PRODUCT_TABLE,
				updateValues, DBManager.PRODUCT_PNO + "=?",
				new String[] { pro.getPno() }) > 0;
	}

	
	private ContentValues createProductValues(
			Product pro) {
		ContentValues values = new ContentValues();
		values.put(DBManager.PRODUCT_PNO, pro.getPno());
		values.put(DBManager.PRODUCT_PARTNO, pro.getPartno());
		values.put(DBManager.PRODUCT_BRAND, pro.getBrandname());
		values.put(DBManager.PRODUCT_MODEL, pro.getPmodel());
		values.put(DBManager.PRODUCT_NPARTNO, pro.getNpartno());
		values.put(DBManager.PRODUCT_PNAME, pro.getPname());
		values.put(DBManager.PRODUCT_PRATE, pro.getPrate());
		values.put(DBManager.PRODUCT_PTYPE, pro.getPtype());
		values.put(DBManager.PRODUCT_PUNITP, pro.getPunitp());
		values.put(DBManager.PRODUCT_PUNITS, pro.getPunits());
		values.put(DBManager.PRODUCT_RATESTR, pro.getRatestr());
		values.put(DBManager.PRODUCT_UNITSTR, pro.getUnitstr());
		return values;
	}

}
